package cn.edu.lingnan.servlet.course;

import cn.edu.lingnan.pojo.Score;
import cn.edu.lingnan.pojo.ScoreDTO;
import cn.edu.lingnan.pojo.User;
import cn.edu.lingnan.service.CourseService;
import cn.edu.lingnan.service.ScoreService;
import cn.edu.lingnan.service.ScoreServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/SelectCourseServlet")
public class SelectCourseServlet extends HttpServlet {
    private ScoreService service=new ScoreServiceImp();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int sid = Integer.parseInt(request.getParameter("sid"));
        int cid = Integer.parseInt(request.getParameter("cid"));
        int grade = Integer.parseInt(request.getParameter("grade"));
        String action = request.getParameter("action");

//        CourseService courseService = new CourseService();
        boolean result;

        if ("select".equals(action)) {
            Score score = new Score();
            score.setSid(sid);
            score.setCid(cid);
            score.setGrade(grade);
            result =  service.addScore(score) != null;
            List<ScoreDTO> courses = service.getCoursesBySid(sid);
            List<ScoreDTO> scores = service.getScoresBySid(sid);
            List<ScoreDTO> noCoursesBySid = service.getNoCoursesBySid(sid);
            request.getSession().setAttribute("courses", courses);
            request.getSession().setAttribute("scores", scores);
            request.getSession().setAttribute("noCoursesBySid", noCoursesBySid);
        } else if ("deselect".equals(action)) {
            result = service.deleteScore(sid, cid) != null;
            List<ScoreDTO> courses = service.getCoursesBySid(sid);
            List<ScoreDTO> scores = service.getScoresBySid(sid);
            List<ScoreDTO> noCoursesBySid = service.getNoCoursesBySid(sid);
            request.getSession().setAttribute("courses", courses);
            request.getSession().setAttribute("scores", scores);
            request.getSession().setAttribute("noCoursesBySid", noCoursesBySid);
        } else {
            result = false;
        }

        if (result) {
            response.getWriter().write("success");
        } else {
            response.getWriter().write("failure");

        }
    }
}